//
//  DetailController.swift
//  SkyApp
//
//  Created by 白翊 on 2021/12/29.
//

import UIKit

class DetailController: BaseViewController {

    //木马一直转动，像走马灯一样，最后会提问题，问题可能有三种：1花木马的个数，2花木马的位置，3第几个是否是花木马，4花木马有几个是倒立的
    
    var difficultType: DifficultType = .easy
    var datas = [MumaDisplay]()
    var chooses = [Bool]()
    let itemSize: CGFloat = 80
    let totalDuration: Double = 30
    var duration: Double = 0  //总时长，秒
    var questionType = QuestionType.one
    weak var timer: Timer?
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        title = "走马观花 · " + difficultType.desc
        
        setupUI()
        
        perform(#selector(ready1), afterDelay: 2.0)
    }
    
    deinit {
        timer?.invalidate()
        timer = nil
        NSObject.cancelPreviousPerformRequests(withTarget: self)
    }
    
    private func setupUI() {
        view.addSubview(titleLabel)
        view.addSubview(timeLabel)
        view.addSubview(collectionView)
        
        timeLabel.font = .init(name: "Futura-Bold", size: 40)
    }
    
    @objc private func ready1() {
        timeLabel.text = "5"
        perform(#selector(ready2), afterDelay: 1.0)
    }
    
    @objc private func ready2() {
        timeLabel.text = "4"
        titleLabel.text = "注意观察所有的图形"
        perform(#selector(ready3), afterDelay: 1.0)
    }
    
    @objc private func ready3() {
        timeLabel.text = "3"
        perform(#selector(ready4), afterDelay: 1.0)
    }
    
    @objc private func ready4() {
        timeLabel.text = "2"
        titleLabel.text = "结束后将会发起提问"
        perform(#selector(ready5), afterDelay: 1.0)
    }
    
    @objc private func ready5() {
        timeLabel.text = "1"
        perform(#selector(begin), afterDelay: 1.0)
        
        for _ in 0..<difficultType.count {
            datas.append(MumaDisplay(isUp: Bool.random(), isFlower: Bool.random()))
        }
        
        collectionView.alpha = 0
        collectionView.reloadData()
    }
    
    @objc private func begin() {
        timeLabel.text = ""
        titleLabel.text = ""

        collectionView.alpha = 1
        collectionView.contentOffset = .init(x: -WIDTH, y: 0)
        
        let timeInterval = 0.01
        let totalDistance = itemSize * CGFloat(difficultType.count) + WIDTH

        timer = Timer.scheduledTimer(withTimeInterval: timeInterval, block: { [weak self] _ in
            guard let self = self else { return }
            
            self.duration += timeInterval
            self.timeLabel.text = String(format: "00:%02d", Int(self.totalDuration - self.duration))
            
            let proportion = self.duration / self.totalDuration
            let distance = totalDistance * proportion
            self.collectionView.contentOffset = .init(x: -WIDTH + distance, y: 0)
            
            if self.duration >= self.totalDuration {
                self.end()
            }
            
        }, repeats: true)
    }
    
    private func end() {
        timer?.invalidate()
        timer = nil
        
        titleLabel.text = "观察已结束"
        timeLabel.isHidden = true
        collectionView.isHidden = true
        
        let questions = [
            QuestionType.one,
            QuestionType.two,
            QuestionType.three,
        ]
        
        let index = Int.random(in: 0..<questions.count)
        questionType = questions[index]
        
        let descLabel = UILabel(string: questionType.desc, fontSize: 14, frame: CGRect(x: interval, y: titleLabel.bottom + interval, width: WIDTH - interval * 2, height: 40), color: .detail, textAlignment: .center)
        view.addSubview(descLabel)
        
        let space: CGFloat = 8
        let rowCount: Int = 5
        let itemSize = (WIDTH - CGFloat(rowCount + 1) * space) / CGFloat(rowCount)
        let height = (itemSize + space) * (CGFloat(difficultType.count) / 5)
        
        chooses.append(contentsOf: Array(repeating: false, count: difficultType.count))
        
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSize(width: itemSize, height: itemSize)
        flowLayout.minimumLineSpacing = space
        flowLayout.minimumInteritemSpacing = space
        
        let collectionView = UICollectionView(frame: CGRect(x: 0, y: descLabel.bottom + interval * 2, width: WIDTH, height: height), collectionViewLayout: flowLayout)
        collectionView.contentInset = UIEdgeInsets(top: 0, left: space - 0.1, bottom: 0, right: space - 0.1)
        collectionView.backgroundColor = .clear
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.showsVerticalScrollIndicator = false
        collectionView.isScrollEnabled = false
        collectionView.register(NumberCell.self, forCellWithReuseIdentifier: "cell")
        collectionView.delegate = self
        collectionView.dataSource = self
        view.addSubview(collectionView)
                
        let sumbitBtn = UIButton(title: "确定", titleColor: .bg, fontSize: 14, frame: CGRect(x: WIDTH * 0.25, y: collectionView.bottom + interval, width: WIDTH * 0.5, height: 40)) { [weak self] _ in
            guard let self = self else {
                return
            }
            SkyAlertView.show(type: .double, title: "提交", desc: "已经确定好你的答案了吗？") {
                self.questionType.judgeResult(choose: self.chooses, datas: self.datas)
                
                self.back()
            }
        }
        sumbitBtn.setCornerRadius(radius: 20)
        sumbitBtn.setThemeGradient()
        view.addSubview(sumbitBtn)
    }
    
    lazy var titleLabel = UILabel(string: "准备好，马上开始游戏", fontSize: 14, frame: CGRect(x: interval, y: interval * 2, width: WIDTH - interval * 2, height: 30), color: .detail, textAlignment: .center)

    lazy var timeLabel = UILabel(frame: CGRect(x: interval, y: titleLabel.bottom + interval, width: WIDTH - interval * 2, height: 80), color: .title, textAlignment: .center)
    
    lazy var collectionView: UICollectionView = {
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.scrollDirection = .horizontal
        flowLayout.itemSize = CGSize(width: itemSize, height: itemSize)
        flowLayout.minimumLineSpacing = 0
        flowLayout.minimumInteritemSpacing = 0
        
        let view = UICollectionView(frame: CGRect(x: 0, y: timeLabel.bottom + interval * 2, width: WIDTH, height: itemSize), collectionViewLayout: flowLayout)
        view.contentInset = UIEdgeInsets(top: 0, left: WIDTH, bottom: 0, right: WIDTH)
        view.backgroundColor = .clear
        view.showsHorizontalScrollIndicator = false
        view.showsVerticalScrollIndicator = false
        view.isScrollEnabled = false
        view.register(MumaView.self, forCellWithReuseIdentifier: "cell")
        view.delegate = self
        view.dataSource = self
        return view
    }()

}

extension DetailController: UICollectionViewDelegate, UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if collectionView != self.collectionView {
            if questionType != .three {
                //只允许单选
                if let alwaysChooseIndex = chooses.firstIndex(where: { $0 }) {
                    chooses[alwaysChooseIndex] = false
                }
            }
            chooses[indexPath.item] = !chooses[indexPath.item]
            collectionView.reloadData()
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if collectionView == self.collectionView {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! MumaView
            cell.display = datas[indexPath.item]
            return cell
        }else {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! NumberCell
            cell.numberLabel.text = questionType == .three ? "\(indexPath.item + 1)" : "\(indexPath.item)"
            cell.choosed = chooses[indexPath.item]
            return cell
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        collectionView == self.collectionView ? datas.count : chooses.count
    }
    
}
